/**
 * @module		vuex 本地储存插件
 * @author      nayo
 * @date        2020/9/23 4:18 下午
 * @version     1.0
 */
import RotStorage from 'rot-storage/dist/rot-storage';

export const merge = (into, from) => {
	return Object.assign({}, into, from);
};

export default class VuexLocalSync {
	constructor(options) {
		this.subscriber = (store) => (handler) => store.subscribe(handler);
		this.key = options.key || 'vuex';
		this.storage = new RotStorage.RotStorage({drive: new RotStorage.drive.LocalStorage()});
		this.reducer = options.reducer != null ? options.reducer : ((state) => state);
		this.restoreState = options.restoreState != null ? options.restoreState : ((key, storage) => {
			const value = (storage).get(key);
			if (typeof value == 'string') {
				return JSON.parse(value) || {};
			} else {
				return (value || {});
			}
		});
		this.saveState = options.saveState != null ? options.saveState : ((key, state, storage) => {
			(storage).set(key, state, 0);
		});
		this.plugin = async (store) => {
			const savedState = this.restoreState(this.key, this.storage);
			let newState = merge(store.state, savedState || {});
			store.replaceState(newState);
			store.subscribe(() => {
				this.saveState(this.key, store.state, this.storage);
			});
		};
	}
}
